from datetime import datetime
import json
from django.shortcuts import render, HttpResponse, redirect
from django.views.decorators.http import require_http_methods

from web.models import Files

def index(request, condition, mode, ID):
    r'''
    :param mode --阅读模式
    :param ID --对应要编辑文本的ID
    
    :example 样例, 你的请求像这样
    
    `{% url 'editView' 'edit|read' ID %}`
    
    `edit, read二选一`
    '''
    return render(request, 'web/editView.html', {
        'condition': condition,
        'mode': mode,
        'ID': ID
    })

@require_http_methods(['GET'])
def queryContent(request, condition):
    ID = request.GET.get('ID', -1)
    file = Files.objects.values('m_time', 'content', 'name').filter(pk=ID)
    if (ID != -1):
        '''
        获取对应ID的文本信息,
        这里可以添加数据库的查找
        '''
        # todo begin
        file_name = file[0]['name']
        content = file[0]['content'].decode('utf8')

        m_time = str(file[0]['m_time']).split('.')[0]
        # todo end
        return HttpResponse(json.dumps({
            'file_name': file_name,
            'content' : content,
            'm_time': m_time
            }),\
            content_type = 'json'
        )
    else:
        return HttpResponse(400)

@require_http_methods(['POST'])
def saveContent(request, condition):
    content = request.POST.get('content', None)
    ID = request.POST.get('ID', None)
    t = Files.objects.get(pk=ID)
    print(t)
    t.content = content.encode('utf8')
    t.m_time = datetime.now()
    t.save()
    # 获取content
    '''
    这里可以对应存储content,
    添加对应数据库的存储
    '''
    # todo begin

    # todo end
    return HttpResponse(200)